<?php
namespace News\Controller;
use Think\Controller;
/**
 * 回执消息查询控制器 ReceiptController.class.php
 */
class ReceiptController extends CommonController{
    //属性声明
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 入口方法
     */
    public function index(){
        $data = I('get.');
        //获取用户userid
        if(!$userid=session($this -> userid_name)){
            $userid = $this -> getUserid($data);
        }

        //记录userid
        //获取该用户发出所有带回执消息
        $news_list = $this -> getNewsList($userid);
        $this -> assign('userid',$userid);
        $this -> assign('news_list',$news_list);
        $this -> assign('corpid',$this->corpid);
        $this -> display();
    }
    
    /**
     * 获取指定用户所有发出消息
     * @param string $userid 用户userid
     */
    private function getNewsList($userid){
        //切换消息数据库
        $GLOBALS['redis'] -> select(1);
        $keys = $GLOBALS['redis'] -> hkeys($this->msg_db_name);
        $index = 0;
        foreach($keys as $k => $v){
            //用户userid
            $temp = explode('_',$v)[0];
            //消息发送时间戳
            $time = explode('_',$v)[1];
            if($temp==$userid){
                $temp_list[$index] = unserialize($GLOBALS['redis'] -> hget($this->msg_db_name,$v));
                //记录时间
                $temp_list[$index]['time'] = $time;
                //记录newsid
                $temp_list[$index]['newsid'] = $v;
                //计算已阅：总数比例
                //1.获取该消息已读成员数量
                $GLOBALS['redis'] -> select(2);
                $has_read_user_count = count($GLOBALS['redis'] -> smembers($this->corpid.'_'.$v));

                //2.获取目标发送成员数量
                $GLOBALS['redis'] -> select(1);
                $data = unserialize($GLOBALS['redis'] -> hget($this->msg_db_name,$v))['sendto'];
                //判断是否全全部成员
                if($data=='all'){
                    $all_send_user_count = count($this -> all_corp_user);
                }else{
                    $all_send_user_count = count(explode(',',$data));
                }
                //3.计算回执比例
                $temp_list[$index]['avg'] = round($has_read_user_count / $all_send_user_count,2)*100; 
                $index++;
            }
        }
        //消息执行排序处理
        $temp_list = $this -> sortNews($temp_list);
        //返回处理结果
        return $temp_list;
    }
    
    /**
     * 消息排序处理
     * @param array $list 消息集合列表
     */
    private function sortNews($list){
        $len = count($list);
        for($i=0;$i<$len-1;$i++){
            for($j=$i+1;$j<$len;$j++){
                if(intval($list[$i]['time'])<intval($list[$j]['time'])){
                    $temp = $list[$i];
                    $list[$i] = $list[$j];
                    $list[$j] = $temp;
                }
            }
        }
        return $list;
    }
    
   
   public function getUserid($data){
       $code = $data['code'];
       if(!$code){
           $this -> error('未经授权用户!');
           exit;
       }
       $access_token = $this -> token;
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}";
       $res = json_decode($this -> https_curl($url),true);
       if(!$userid = $res['UserId']){
           $this -> error('未经授权用户!');
       }
       session($this->userid_name,$userid);
       return $userid;
   }
   
   /**
    * 获取指定消息统计信息
    */
   public function getCount(){
       //获取newsid
       if(!$news_id = I('get.newsid')){
           $this -> error('非法参数传递!');
       }
       //获取该消息目标推送所有成员
       $GLOBALS['redis'] -> select(1);
       $data = unserialize($GLOBALS['redis'] -> hget($this->msg_db_name,$news_id))['sendto'];
       //获取缓存数据
       $all_user_list = $this -> all_corp_user;

       if($data != 'all'){
           //非全选情况
           $choose_list = explode(',',$data);
           //部门 成员
           //获取已读消息成员数据
           $GLOBALS['redis'] -> select(2);
           $has_read_list = $GLOBALS['redis'] -> smembers($this->corpid.'_'.$news_id);
           //获取已读消息成员读取状态数据
           $has_read_info_list = $GLOBALS['redis'] -> smembers($this->corpid.'_'.$news_id.'-status');
           //整理分析未读消息成员集合
           $unread_list = [];
           foreach($choose_list as $k => $v){
               if(!in_array($v,$has_read_list)){
                   $unread_list[] = $v;
               }
           }

           $has_read_list2 = [];
           $unread_list2 = [];
           //分配成员属性数据
           foreach($all_user_list as $k => $v){
               if(in_array($v['userid'],$has_read_list)){
                   $has_read_list2[] = $v;
               }
               if(in_array($v['userid'],$unread_list)){
                   $unread_list2[] = $v;
               }
           }
           //计数统计
           $count_has_read = count($has_read_list);
           $count_total = count($choose_list);
           $count_avg = round($count_has_read/$count_total,2)*100;
       }else{
           //选择所有人
           //获取已读消息成员数据
           $GLOBALS['redis'] -> select(2);
           $has_read_list = $GLOBALS['redis'] -> smembers($this->corpid.'_'.$news_id);
           //整理分析未读消息成员集合
           $unread_list = [];
           foreach($all_user_list as $k => $v){
               if(!in_array($v['userid'],$has_read_list)){
                   $unread_list[] = $v['userid'];
               }
           }
           $has_read_list2 = [];
           $unread_list2 = [];
           //分配成员属性数据
           foreach($all_user_list as $k => $v){
               if(in_array($v['userid'],$has_read_list)){
                   $has_read_list2[] = $v;
               }
               if(in_array($v['userid'],$unread_list)){
                   $unread_list2[] = $v;
               }
           }
           //计数统计
           $count_has_read = count($has_read_list);
           $count_total = count($all_user_list);
           $count_avg = round($count_has_read/$count_total,2)*100;
       }
       //已读传递
       $this -> assign(array(
           'count_has_read' => $count_has_read,
           'count_total' => $count_total,
           'count_avg' => $count_avg,
       ));
       //写入读取状态信息
       $temp_list = [];
       foreach($has_read_info_list as $k => $v){
           $data = explode('-',$v);
           //读取用时
           $temp_list[$data[0]]['read_for_time'] = $data[1];
           //读取时间
           $temp_list[$data[0]]['read_time'] = $data[2];
       }
       $user_short_time_list = [];
       foreach($has_read_list2 as $k => $v){
           $userid = $v['userid'];
           if($temp_list[$userid]){
               $has_read_list2[$k]['info'] = $temp_list[$userid];
               //提取读取消息小于两秒用户集合
               if($temp_list[$userid]['read_for_time']<2){
                   $user_short_time_list[] = $has_read_list2[$k];
               }
           }else{
               $has_read_list2[$k]['info'] = array();
           }
       }
       $this -> assign('user_short_time_list',$user_short_time_list);

       $this -> assign('has_read_list',$has_read_list2);
       //未读传递
       $this -> assign('unread_list',$unread_list2);
       //消息id传递
       $this -> assign('news_id',$news_id);
       $this -> display();
   }
   
   /**
    * 删除全部消息
    */
   public function deleteAll(){
       $data = I('get.');
       $userid = $data['userid'];
       //删除消息源
       $GLOBALS['redis'] -> select(1);
       $keys = $GLOBALS['redis'] -> hkeys($this->msg_db_name);
       foreach($keys as $k => $v){
            $temp = explode('_',$v)[0];
            $time = explode('_',$v)[1];
            if($temp==$userid){
                $GLOBALS['redis'] -> select(1);
                $GLOBALS['redis'] -> hdel($this->msg_db_name,$v);
                $GLOBALS['redis'] -> del($v);
                //删除回执记录信息
                $GLOBALS['redis'] -> select(2);
                $GLOBALS['redis'] -> del($this->corpid.'_'.$v.'-status');
                $GLOBALS['redis'] -> del($this->corpid.'_'.$v);
            }
       }
       $this -> success('删除成功!',U('index',array('state'=>$this->corpid)));
   }
   
   /**
    * 删除单条消息
    */
   public function del_single(){
       $data = I('get.');
       $newsid = $data['newsid'];
       //1.删除消息库消息记录
       $GLOBALS['redis'] -> select(1);
       $GLOBALS['redis'] -> hdel($this->msg_db_name,$newsid);
       //2.删除回执库回执记录
       $GLOBALS['redis'] -> select(2);
       $GLOBALS['redis'] -> del($this->corpid.'_'.$newsid);
       $GLOBALS['redis'] -> del($this->corpid.'_'.$newsid.'-status');
       $this -> success('删除成功!',U('index',array('state'=>$this->corpid)));
   }
}